function formatDate(d) {
  return d.getFullYear() + '-' + zeroPad(d.getMonth()+1, 2) + '-' + zeroPad(d.getDate(), 2);	
}

function parseDate(input) {
  ds = input.value;
  var re = /\b(1[0-2]|0?[1-9])[\-\/](0[1-9]|[12][0-9]|3[01]|[1-9])[\-\/]?(\d{2,4})?/;
  var a = re.exec(ds);
  if (a) {
      var m = a[1]-1;
      var d = a[2];
      var y = a[3];
      if (y) {
	      if (y.length < 4)
          y = '20' + y;
	    }
      else {
        y = new Date();
        y = y.getFullYear();
      }
      var oDate = new Date(y,m,d);
      input.value = formatDate(oDate);
      return oDate;
  } 
	else {
		re = /\b(today|now|t)([-\+\s])?(\d{1,3})?/;
		a = re.exec(ds);
		if (a) {
		  oDate = new Date();
		  var sign = a[2];
		  var offset = a[3];
		  if (offset) {
			if (sign == '-') c = -1; else c = 1;
		    var ms = oDate.getTime() + (c * (offset * 24 * 60 * 60 * 1000));
		    oDate = new Date(ms);
		  }
		  input.value = formatDate(oDate);
		  return oDate;
		}
		else {
		  input.value = 'invalid';
	      return null;
      }
  }
}

function zeroPad(n,d)
{
  var ns = n + '';
  while(ns.length < d) {
    ns = '0' + ns;
  }
  return ns;
}
